#include "USART.h"
#include "..\UserOS\OS_Event.h"

// uint8 USART_TxBuf[MAX_TXBUF_SIZE];
vuint8 USART_RxBuf[MAX_RXBUF_SIZE];
vuint8 USART_RxIdx;
uint8 USART_RxCnt;
uint8 USART_CntRxTimeOut;

void initUSART(void)
{
    SPBRG = BAUDRATE_CFG;
    TXSTA = TXSTA_CFG;
    RCSTA = RCSTA_CFG;

    EN_RX_INT();
    DIS_TX_INT();

    // memset(USART_TxBuf,0,sizeof(USART_TxBuf));
    memset(USART_RxBuf,0,sizeof(USART_RxBuf));
    USART_RxCnt = 0;
    USART_RxIdx = 0;
}

void USART_SendByte(uint8 dat)
{
    USART_TX_DATA(dat);
}

void USART_SendBuf(uint8* buf, uint8 size)
{
    uint8 i;
    for(i=0; i<size; i++)
    {
        USART_TX_DATA(buf[i]);
    }
}

void USART_RecvProc(void)
{
    USART_RxBuf[USART_RxIdx++] = RCREG;
    if(USART_RxIdx >= MAX_RXBUF_SIZE)
    {
        USART_RxIdx = 0;
    }
    USART_CntRxTimeOut = 0;
}

void USART_TimeProc(void)
{
    if(USART_RxIdx)
    {
        USART_CntRxTimeOut++;
        if(USART_CntRxTimeOut >= MAX_TIMEOUT_RX)
        {
            USART_CntRxTimeOut = 0;
            if(USART_RxIdx >= MIN_RX_COUNT)
            {
                USART_RxCnt = USART_RxIdx;
                OS_SetEvent(OS_EVENT_USART_RX_TIME_OUT);
            }
            USART_RxIdx = 0;
        }
    }
}